#ifndef ADAM_DATABASE_TABLE_H
#define ADAM_DATABASE_TABLE_H

#include "ccstring.h"
#include "condition.h"
#include <stdio.h>
#include <pthread.h>

struct row {
  struct string **cols;
};

struct col_name_value_pair {
  struct string *col_name;
  struct string *col_value;
};

enum col_type { TYPE_CHAR = 0, TYPE_INT = 1 };

struct col_def {
  struct string *col_name;
  enum col_type col_type;
  int length;
};

struct table {
  struct string *table_name;
  struct col_def **col_defs;
  int col_count;
  int row_length;
  pthread_rwlock_t rwlock_for_data;
  pthread_rwlock_t rwlock_for_tx;
};

/**
 * 在内存中返回一张表的实例，并不会进行任何硬盘操作
 */
struct table *table_new(struct string *table_name);

/**
 * 在内存中添加表的列定义
 */
void table_add_col_def(struct table *T, struct string *col_name,
                       enum col_type col_type, int length);

struct string *_table_read_value_from_file(FILE *fp, int length);

bool _table_row_match_condition(struct table *T, struct condition **conditions,
                                int condition_count, FILE *fp, int row_index);

bool _table_row_is_empty(struct table *T, FILE *fp, int row_index);

int _table_get_col_offset(struct table *T, int col_index);

struct col_name_value_pair *
table_col_name_value_pair_new(struct string *col_name,
                              struct string *col_value);

struct col_name_value_pair *
table_find_col_name_value_pair(struct col_name_value_pair **pairs,
                               int pair_count, struct string *col_name);

void table_col_name_value_pair_free(struct col_name_value_pair *pair);

/**
 * 释放表所占用的内存空间
 * @param *T 表
 */
void table_free(struct table *T);

#endif
